  <script setup lang="ts">
import {ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import CdlForm from "@/components/form";
import type {FormTree} from "@/interfaces/components/Form";
import type {Authentication, Driver} from "@/interfaces/views/vehicle/driver";
import type {FormData} from "@/interfaces/components/Page";
import {appStore} from "@/store/modules/app";
import {useDriverInsertApi, useDriverUpdateApi, useGetDriverInfoApi, useGetFleetListApi} from "@/api/vehicle/driver";
import {ElMessage} from "element-plus/es";
import {mergeObjects} from "@/utils/utilities";
import constant from "@/utils/constant";

const router = useRouter()
const route = useRoute()
const store = appStore()
if(route.query.id) initData()

const basicFormTree: FormTree<Driver> = [
    [
      {label: "司机姓名", component: "input", prop: "name", rule: [
          {required: true, message: '必须填写司机名称', trigger: 'blur'},
          {min: 2, max: 18, message: '司机名称应该在2-18个字符之间', trigger: 'blur'},
        ]},
      {label: "司机手机号码", component: "input", prop: "mobile", rule:[{
          required: true, message: '必须填写司机手机号', trigger: 'blur'
        }, {
          pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
          message: '请输入正确电话号码',
        }]},
      {label: "所属车队", component: "select", prop: "fleetId", serviceOptionKey: "fleet",
        optionProps:{label:"name",value:"id"}, disabled: !!route.query.id},
    ],
    [
      {label: "认证状态", component: "tag", prop: "status", dict: "driver_status"},
      {label: "登录密码", component: "input", prop: "password", placeholder: "默认手机号后四位", rule: [
          {min: 4, max: 12, message: '密码应该在4-12个字符之间', trigger: 'blur'},
        ], enable: !route.query.id},
      {}
    ],
    [
      {label: "备注", component: "input", prop: "remark", type: "textarea"}
    ]
]
const authenticationFormTree: FormTree<Authentication> = [
    [
      {label: "紧急联系人", component: "input", prop: "emergencyContact", rule: [
          {required: true, message: '必须填写紧急联系人', trigger: 'blur'}
        ]},
      {label: "身份证号码", component: "input", prop: "idNum", rule: [
          {required: true, message: '必须填写司机身份证', trigger: 'blur'},
          {pattern: /(^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}(\d|X)$)/,
            message: "请输入正确的身份证"}
        ]},
      {label: "银行卡号", component: "input", prop: "creditCardNum", rule: [
          {required: true, message: '必须填写银行卡号', trigger: 'blur'},
          {pattern: /^([1-9])(\d{14}|\d{18})$/, message: "请输入正确的银行卡号"}
        ]}
    ],
    [
      {label: "紧急联系人手机号", component: "input", prop: "emergencyContactPhone", rule: [
          {required: true, message: '必须填写紧急联系人手机号', trigger: 'blur'},
          {pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确电话号码'}
        ]},
      {label: "驾驶证发证机关", component: "input", prop: "drivingLicenseIssuingAuthority", rule: [
          {required: true, message: '必须填写驾驶证签发机关', trigger: 'blur'}
        ]},
      {label: "驾驶证有效期", component: "input", },
    ],
    [
      {label: "驾驶证号", component: "input", prop: "drivingLicenseNum", rule: [
          {required: true, message: '必须填驾驶证号', trigger: 'blur'}
        ]},
      {label: "从业资格证编号", component: "input", prop: "qualificationCertificateNum", rule: [
          {required: true, message: '必须填写从业资格证编号', trigger: 'blur'}
        ]},
      {label: "居住地址", component: "input", prop: "address", rule: [
          {required: true, message: '必须填写居住地址', trigger: 'blur'},
          {min: 2, max: 32, message: '居住地址应该在2-32个字符之间', trigger: 'blur'}
        ]},
    ],
    [
      {label: "身份证正面", component: "upload", prop: "idCardObvImg", rule: [
          {required: true, message: '必须上传身份证正面照', trigger: 'blur'}
        ], action: constant.uploadUrl},
      {label: "身份证背面", component: "upload", prop: "idCardRevImg", rule: [
          {required: true, message: '必须上传身份证反面照', trigger: 'blur'}
        ], action: constant.uploadUrl},
      {label: "驾驶证", component: "upload", prop: "drivingLicenseImg", rule: [
          {required: true, message: '必须上传驾驶证照片', trigger: 'blur'}
        ], action: constant.uploadUrl},
    ],
    [
      {label: "道路运输从业资格证", component: "upload", prop: "transportPermitImg", rule: [
          {required: true, message: '必须上传道路运输从业资格证', trigger: 'blur'}
        ], action: constant.uploadUrl},
      {label: "手持证件照", component: "upload", prop: "peopleLicenseImg", rule: [
          {required: true, message: '必须上传手持证件照', trigger: 'blur'}
        ], action: constant.uploadUrl},
      {}
    ]
]

const basicData = ref<FormData<Driver>>({
  id: undefined,
  name: "",
  mobile: "",
  password: "",
  status: 1,
  fleetId: undefined,
  remark: ""
})
const authenticationData = ref<FormData<Authentication>>({
  emergencyContact: "",
  idNum: "",
  emergencyContactPhone: "",
  drivingLicenseIssuingAuthority: "",
  drivingLicenseEffectiveTime: "",
  drivingLicenseExtTime: "",
  drivingLicenseNum: "",
  qualificationCertificateNum: "",
  address: "",
  creditCardNum: "",
  idCardObvImg: "",
  idCardRevImg: "",
  drivingLicenseImg: "",
  transportPermitImg: "",
  peopleLicenseImg: ""
})
const basicRef = ref()
const authenticationRef = ref()

/**
 * 提交
 */
async function submit(){
  const basic = await basicRef.value.parentSubmit()
  let authentication = {}
  if(basicData.value.status === 1) authentication = await authenticationRef.value.parentSubmit()
  const data: {[key: string]: any} = {}
  Object.assign(data, basic, authentication)
  if(route.query.id) {
    useDriverUpdateApi(data).then(() => {
      ElMessage.success("修改成功！自动跳转上一页")
      fallbackPage()
    })
  }else {
    data.password = data.mobile.slice(-4)
    useDriverInsertApi(data).then(() => {
      ElMessage.success("新增成功！自动跳转上一页")
      fallbackPage()
    })
  }
}

/**
 * 初始化数据
 */
function initData(){
  useGetDriverInfoApi(route.query.id as string).then(res =>{
    mergeObjects(basicData.value, res.data)
    mergeObjects(authenticationData.value, res.data)
  })
}

/**
 * 获取车队列表
 */
function getFleetList(){
  return new Promise((resolve) => {
    useGetFleetListApi().then(res => {
      resolve(res.data)
    })
  })
}

/**
 * 回退页面
 */
function fallbackPage(){
  router.back()
}
</script>

<template>
  <el-card style="position: relative">
    <button class="back_btn" @click="fallbackPage"></button>
    <h1 class="top_line">基础信息</h1>
    <el-divider></el-divider>
    <CdlForm ref="basicRef" :model="basicData" :template-tree="basicFormTree"  label-width="110"
             :init="{fleet: getFleetList}"></CdlForm>
    <div v-show="basicData.status === 2">
      <h1>认证信息</h1>
      <el-divider></el-divider>
      <CdlForm ref="authenticationRef" :model="authenticationData" :template-tree="authenticationFormTree"
               label-width="140"></CdlForm>
    </div>
    <div class="footer_btn">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="fallbackPage">取消</el-button>
    </div>
  </el-card>
</template>
